<template>
  <div>
    <div class="select-frame flex items-center justify-between">
      <!-- 是否启用夜班 -->
      <div v-for="item in formData" :key="item.period" :class="getSystemConfig('ENABLE_NIGHT_OUTPATIENT') === '1' ? 'w-1/3' : 'w-1/2'" class="border-r-2 pr-2">
        <div class="relative">
          <EditCell title="上午班制 ">
            <SelectTable v-model:value="item.schedulingName" type="班制" @clear="item.schedulingId = ''" @select="onSelectShifts($event, item)" />
          </EditCell>
        </div>
        <div class="mt-2 relative">
          <EditCell title="上午诊室 ">
            <SelectTable v-model:value="item.roomName" type="诊室" @clear="item.roomId = ''" @select="onSelectRoom($event, item)" />
          </EditCell>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue'
import EditCell from '@/components/EditCell'
import SelectTable from '@/components/SelectTable'
import { post } from '@/utils/request'
import { getSystemConfig } from '@/utils/systemConfig'

const emit = defineEmits(['success'])
const props = defineProps({
  empData: {
    type: Object,
    default: () => ({})
  }
})
const formData = ref([])
const onSelectShifts = (value, option) => {
  option.schedulingId = value.id
  option.schedulingName = value.schedulingName
  onChange()
}
const onSelectRoom = (value, option) => {
  option.roomId = value.id
  option.roomName = value.roomName
  onChange()
}
const onChange = () => {
  emit('success')
}
const getRoomName = async (data) => {
  if (!data) return ''
  const res = await post('/operation/opex/getRoomList', {
    pyjm: data,
    pageSize: 10,
    pageNum: 1
  })
  if (res.code !== 0) return
  return res.data[0]?.roomName
}
const getSchedulingName = async (data) => {
  if (!data) return ''
  const res = await post('operation/opex/getSchedulingDictList', {
    pyjm: data,
    pageSize: 10,
    pageNum: 1
  })
  if (res.total) {
    return res.data[0]?.schedulingName
  } else {
    return ''
  }
}

onMounted(() => {
  formData.value = props.empData.map((item) => {
    getRoomName(item.roomId).then((data) => {
      item.roomName = data
    })
    getSchedulingName(item.schedulingId).then((data) => {
      item.schedulingName = data
    })

    return item
  })
  if (getSystemConfig('ENABLE_NIGHT_OUTPATIENT') !== '1') formData.value.pop() //是否启用夜班
})
watch(
  () => props.empData,
  () => {
    formData.value = props.empData.map((item) => {
      getRoomName(item.roomId).then((data) => {
        item.roomName = data
      })
      getSchedulingName(item.schedulingId).then((data) => {
        item.schedulingName = data
      })

      return item
    })
    if (getSystemConfig('ENABLE_NIGHT_OUTPATIENT') !== '1') formData.value.pop()
  }
)
</script>
<style lang="less" scoped>
.select-frame {
  .relative {
    height: 30px;
  }
  .border-r-2:last-child {
    border-right: 0 !important;
  }
}
</style>
